// Copyright 2025 piko
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use client'
import React, { useState, useEffect, useCallback } from 'react';
import { userService, type User as ServiceUser } from '@/service/user.service';
// 导入React 19兼容的消息提示方式
import { notification } from 'antd';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Space,
  Typography,
  Pagination,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { formatDate } from '@/util/util';

const { Title, Text } = Typography;
const { Option } = Select;

// 用户数据类型定义（扩展服务中的User接口）
interface User extends ServiceUser {
  isActive: boolean; // 计算属性，基于status
  bio?: string;
}

// 从status转换为isActive
const statusToIsActive = (status?: number): boolean => {
  return status === 1; // 1表示启用
};

// 从isActive转换为status
const isActiveToStatus = (isActive: boolean): number => {
  return isActive ? 1 : 0; // 1启用，0禁用
};

export default function UserList() {
  // 状态管理
  const [users, setUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();
  const [addForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [totalUsers, setTotalUsers] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState({id: 0, username: ''});

  // 获取用户列表
  const fetchUsers = async (page: number = 1, keyword: string = '') => {
    setLoading(true);
    try {
      const response = await userService.getUserList({
        page,
        pageSize,
        keyword
      });
      console.log('response:  ', response);
      // 处理API响应数据格式
      if (response && response.data) {
        // 使用API返回的用户数据列表
        const formattedUsers = (response.data as ServiceUser[]).map((user: ServiceUser) => ({
          ...user
        }));
        
        setUsers(formattedUsers as []);
        setFilteredUsers(formattedUsers as []);
        console.log('formattedUsers:  ', formattedUsers);
        // 更新分页相关数据 - 从response.data中获取分页信息
        // 分页数据
        setCurrentPage(response.page || 1);
        setPageSize(response.pageSize || 10);
        setTotalUsers(response.total || 0);
        setTotalPages(response.totalPages || 1);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      // 使用notification替代message避免React 19兼容性问题
      notification.error({
        message: '获取用户列表失败',
        description: error instanceof Error ? error.message : '未知错误'
      });
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和页面/搜索条件变化时获取数据
  useEffect(() => {
    fetchUsers(currentPage, searchKeyword);
  }, [currentPage]);

  // 处理搜索
  const handleSearch = () => {
    setCurrentPage(1); // 搜索时重置到第一页
    fetchUsers(1, searchKeyword);
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchKeyword('');
    setCurrentPage(1);
    fetchUsers(1, '');
  };

  // 由于后端已处理分页，直接使用filteredUsers
  const paginatedUsers = filteredUsers;

  // 打开编辑模态框
  const handleEdit = (user: User) => {
    setEditingUser(user);
    // 设置所有需要编辑的字段
    form.setFieldsValue({
      bio: user.bio || '',
      password: '' // 密码字段始终为空
    });
    setIsEditModalVisible(true);
  };

  // 打开添加用户模态框
  const handleAddUser = () => {
    addForm.resetFields();
    setIsAddModalVisible(true);
  };

  // 关闭添加用户模态框
  const handleCancelAdd = () => {
    setIsAddModalVisible(false);
    addForm.resetFields();
  };

  // 添加用户
  const handleAddUserSubmit = async () => {
    addForm.validateFields().then(async (values) => {
      try {
        setLoading(true);
        // 构建用户数据
        const userData: Partial<ServiceUser> = {
          username: values.username,
          email: values.email,
          password: values.password, 
          role: values.role || 0, // 默认普通用户
          status: 1 // 新用户默认启用
        };
        
        // 调用服务添加用户
        await userService.createUser(userData as any);
        notification.success({
          message: '用户添加成功'
        });
        setIsAddModalVisible(false);
        addForm.resetFields();
        
        // 重新获取用户列表
        fetchUsers(currentPage, searchKeyword);
      } catch (error) {
        notification.error({
          message: '添加用户失败',
          description: error instanceof Error ? error.message : '未知错误'
        });
        console.error('添加用户失败:', error);
      } finally {
        setLoading(false);
      }
    });
  };

  // 关闭编辑模态框
  const handleCancel = () => {
    setIsEditModalVisible(false);
    form.resetFields();
  };

  // 保存编辑的用户信息（修改密码和bio字段）
  const handleSave = async () => {
    form.validateFields().then(async values => {
      if (editingUser) {
        try {
          // 创建更新对象
          const updateData: Partial<User> = {};
          
          // 只更新有变化的字段
          if (values.bio !== undefined) {
            updateData.bio = values.bio; // 假设后端使用bio存储简介
          }
          
          // 如果密码不为空，则重置密码
          if (values.password) {
            updateData.password = values.password;
          }
          
          // 更新用户信息
          if (Object.keys(updateData).length > 0) {
            await userService.updateUser(editingUser.id, updateData);
          }
          
          notification.success({
            message: '用户信息更新成功'
          });
          // 重新获取用户列表以更新数据
          fetchUsers(currentPage, searchKeyword);
        } catch (error) {
          notification.error({
            message: '更新用户信息失败',
            description: error instanceof Error ? error.message : '未知错误'
          });
          console.error('更新用户信息失败:', error);
        }
      }
      setIsEditModalVisible(false);
      form.resetFields();
    });
  };

  // 打开删除确认对话框
  const handleDelete = (userId: number, username: string) => {
    setDeleteTarget({ id: userId, username });
    setDeleteModalVisible(true);
  };

  // 确认删除用户
  const confirmDelete = async () => {
    try {
      setLoading(true);
      // 调用服务删除用户
      const deletedUser = await userService.deleteUser(deleteTarget.id);  
      notification.success({
        message: '删除成功',
        description: `用户 ${deleteTarget.username} 已成功删除`
      });
      // 重新获取用户列表
      // 如果当前页面只有一条记录且不是第一页，则返回到上一页
      const newPage = (users.length === 1 && currentPage > 1) ? currentPage - 1 : currentPage;
      fetchUsers(newPage, searchKeyword);
      setDeleteModalVisible(false);
    } catch (error) {
      notification.error({
        message: '删除失败',
        description: error instanceof Error ? error.message : '未知错误，请稍后重试'
      });
    } finally {
      setLoading(false);
    }
  };

  // 切换用户状态
  const handleStatusChange = async (userId: number, newStatus: boolean) => {
    try {
      await userService.updateUserStatus(userId, isActiveToStatus(newStatus));
      notification.success({
        message: `用户状态已${newStatus ? '启用' : '封禁'}`
      });
      // 重新获取用户列表
      fetchUsers(currentPage, searchKeyword);
    } catch (error) {
      notification.error({
        message: '更新用户状态失败',
        description: error instanceof Error ? error.message : '未知错误'
      });
      console.error('更新用户状态失败:', error);
    }
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {        title: '角色',
        dataIndex: 'role',
        key: 'role',
        render: (role?: number) => {
          const roleMap: Record<number, { text: string; color: string; bgColor: string }> = {
            0: { text: '普通用户', color: '#1677ff', bgColor: '#e6f7ff' },
            1: { text: '管理员', color: '#d4380d', bgColor: '#fff7e6' },
          };
          const roleInfo = roleMap[role || 0] || { text: '未知', color: '#8c8c8c', bgColor: '#f5f5f5' };
          return (
            <span
              style={{
                display: 'inline-block',
                padding: '4px 12px',
                borderRadius: '16px',
                fontSize: '12px',
                fontWeight: 500,
                color: roleInfo.color,
                backgroundColor: roleInfo.bgColor,
                border: `1px solid ${roleInfo.color}33`,
              }}
            >
              {roleInfo.text}
            </span>
          );
        },
      },
      {        title: '状态',
        dataIndex: 'isActive',
        key: 'isActive',
        render: (isActive: boolean) => {
          const statusInfo = isActive 
            ? { text: '正常', color: '#52c41a', bgColor: '#f6ffed' }
            : { text: '封禁', color: '#ff4d4f', bgColor: '#fff1f0' };
          return (
            <span
              style={{
                display: 'inline-block',
                padding: '4px 12px',
                borderRadius: '16px',
                fontSize: '12px',
                fontWeight: 500,
                color: statusInfo.color,
                backgroundColor: statusInfo.bgColor,
                border: `1px solid ${statusInfo.color}33`,
              }}
            >
              {statusInfo.text}
            </span>
          );
        },
      },
    {
      title: '简介',
      dataIndex: 'bio',
      key: 'bio',
      ellipsis: true,
      render: (bio: string) => <Text title={bio}>{bio || '无简介'}</Text>,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: Date) => formatDate(date.toLocaleString()),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      render: (date: Date) => formatDate(date.toLocaleString()),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: User) => (
        // 管理员用户(role == 1)不显示任何操作按钮
        !record.role || record.role !== 1 ? (
          <Space size="middle">
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            >
              编辑
            </Button>
            <Switch
              checked={record.isActive}
              onChange={(checked) => handleStatusChange(record.id, checked)}
              checkedChildren="正常"
              unCheckedChildren="封禁"
              size="small"
            />
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record.id, record.username)}
            >
              删除
            </Button>
          </Space>
        ) : null
      ),
    },
  ];

  return (
    <div className="p-6 bg-white min-h-screen">
      <div className="flex justify-between items-center mb-6">
        <Title level={2} className="m-0">
          <UserOutlined /> 用户管理
        </Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>
            添加用户
          </Button>
      </div>
      
      {/* 删除确认对话框 */}
      <Modal
        title="确认删除用户"
        open={deleteModalVisible}
        onOk={confirmDelete}
        onCancel={() => setDeleteModalVisible(false)}
        okText="确认删除"
        cancelText="取消"
        okType="danger"
        confirmLoading={loading}
      >
        <div>
          <p style={{ color: '#ff4d4f', marginBottom: '8px' }}>此操作不可撤销！</p>
          <p>确定要删除用户 <strong>{deleteTarget.username}</strong> 吗？</p>
          <p style={{ color: '#8c8c8c', marginTop: '8px', fontSize: '14px' }}>删除后，该用户的所有数据将被永久移除。</p>
        </div>
      </Modal>

      {/* 搜索区域 */}
      <div className="mb-4 p-4 bg-gray-50 rounded">
        <Space>
          <Input
            placeholder="搜索用户名或邮箱"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: 300 }}
          />
          <Button type="primary" onClick={handleSearch}>搜索</Button>
          <Button onClick={handleResetSearch}>重置</Button>
        </Space>
      </div>

      {/* 用户表格 */}
      <Table
        columns={columns}
        dataSource={paginatedUsers}
        rowKey="id"
        pagination={false}
        scroll={{ x: 'max-content' }}
        loading={loading}
        className="mb-4"
      />

      {/* 分页器 - 使用API返回的数据 */}
      <div className="flex justify-end">
        <Pagination
          current={currentPage}
          onChange={setCurrentPage}
          pageSize={pageSize}
          total={totalUsers}
          showSizeChanger={false}
          showTotal={(total) => `共 ${total} 条记录，第 ${currentPage} / ${totalPages} 页`}
          disabled={loading}
        />
      </div>

      {/* 编辑用户模态框 */}
      <Modal
        title="编辑用户"
        open={isEditModalVisible}
        onOk={handleSave}
        onCancel={handleCancel}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        {editingUser && (
          <div className="mb-4">
            <div className="text-sm text-gray-500 mb-2">当前编辑用户：</div>
            <div className="p-3 bg-gray-50 rounded">
              <div><strong>ID:</strong> {editingUser.id}</div>
              <div><strong>用户名:</strong> {editingUser.username}</div>
              <div><strong>邮箱:</strong> {editingUser.email}</div>
              <div><strong>角色:</strong> {editingUser.role === 0 ? '普通用户' : '管理员'}</div>
              <div><strong>状态:</strong> {editingUser.isActive ? '正常' : '封禁'}</div>
            </div>
          </div>
        )}
        
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="password"
            label="密码"
            tooltip="留空表示不修改密码"
            rules={[
              { 
                pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/,
                message: '密码至少8位，包含字母和数字',
                whitespace: false
              }
            ]}
          >
            <Input.Password 
              placeholder="请输入新密码（留空表示不修改）"
              allowClear
            />
          </Form.Item>
          
          <Form.Item
          name="bio"
          label="个人简介"
        >
          <Input.TextArea 
            placeholder="请输入个人简介"
            rows={4}
            maxLength={200}
            showCount
          />
        </Form.Item>
        </Form>
      </Modal>

      {/* 添加用户模态框 */}
      <Modal
        title="添加用户"
        open={isAddModalVisible}
        onOk={handleAddUserSubmit}
        onCancel={handleCancelAdd}
        okText="添加"
        cancelText="取消"
        width={600}
        confirmLoading={loading}
      >
        <Form
          form={addForm}
          layout="vertical"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, max: 20, message: '用户名长度应在3-20个字符之间' }
            ]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱地址" />
          </Form.Item>
          
          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { 
                pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/,
                message: '密码至少8位，包含字母和数字',
                whitespace: false
              }
            ]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          
          <Form.Item
            name="role"
            label="角色"
            initialValue={0}
          >
            <Select placeholder="请选择用户角色">
              <Option value={0}>普通用户</Option>
              <Option value={1}>管理员</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
